"use strict"

let UniV3_Claimable         = "0"
let UniV3_RewardsSeconds    = "0"
let UniV3_RewardTime        = 0
let UniV3_Liquidity         = 0

let balance_cb              = 0
let balance_usdt            = 0
let cbPrice                 = 0
let callAddLiquidity        = true;

let GamingLP_Claimable      = "0"
let GamingLP_RewardsSeconds = "0"
let GamingLP_RewardTime     =  0
let GLP_liquidity           =  0


function onLogin()
{
    onInitLiquidity();

    UniV3_ClaimableLoop();
    CheckApproveLoop();

    GLP_ClaimableLoop()
    GLP_CheckApproveLoop()
}

async function onInitLiquidity()
{
    allowCB   = -1;
    allowUSDT = -1;
    GLP_allowUSDT = -1;
    
    var contractCB      = GetContractERC20(Contract_CB);
    var contractUSDT    = GetContractERC20(Contract_USDT);
    var contractUniV3   = GetContractUniV3();

    // doApproveToUniV3(Contract_CB,"1");
    // doApproveToUniV3(Contract_USDT,"1");
    
    RefreshRewardsSeconds();
    RefreshAllow();

    balance_cb   = await contractCB.balanceOf(Helper.addressCur);
    balance_usdt = await contractUSDT.balanceOf(Helper.addressCur);
    balance_cb   = window._ethers.utils.formatUnits(balance_cb, Contract_Decimals)
    balance_usdt = window._ethers.utils.formatUnits(balance_usdt, Contract_Decimals)
    balance_cb   = Helper.Fix2(balance_cb)
    balance_usdt = Helper.Fix2(balance_usdt)

    $("#balance_cb")  .html("Balance: " +   balance_cb );
    $("#balance_usdt").html("Balance: " + balance_usdt );

    try{
        UniV3_Liquidity  = await contractUniV3.GetLiquidity(Helper.addressCur);
        UniV3_Liquidity  = Helper.Fix2(window._ethers.utils.formatUnits(UniV3_Liquidity, Contract_Decimals));
        $("#UniV3_Liquidity").html("Liquidity: " + UniV3_Liquidity );
        callAddLiquidity = false;
    }
    catch(e)
    {
        callAddLiquidity = true;
    }

    // ------------------------------------------------------------------------------------
    // GLP
    // ------------------------------------------------------------------------------------
    $("#GLP_balance_usdt").html("Balance: " + balance_usdt );

    var contractGamingLP = GetContractGamingLP();

    // var totalSupply = await contractGamingLP.totalSupplyToken();
    // totalSupply = Helper.Fix2(window._ethers.utils.formatUnits(totalSupply, Contract_Decimals))
    // $("#GLP_totalSupply").html(totalSupply);

    GLP_liquidity = await contractGamingLP.balanceOf(Helper.addressCur);
    GLP_liquidity = Helper.Fix2(window._ethers.utils.formatUnits(GLP_liquidity, Contract_Decimals))
    $("#GLP_liquidity").html("Deposited: "+GLP_liquidity);

    // ------------------------------------------------------------------------------------
    // cbPrice 
    // ------------------------------------------------------------------------------------
    var contractUNIHelper   = GetContractUNIHelper();
    try{    
        cbPrice = await contractUNIHelper.getPrice(Contract_UNIV3_NFT);
        cbPrice = window._ethers.utils.formatUnits(cbPrice, 6)
    }
    catch(e)
    {
    }
    if(cbPrice=="0.0")cbPrice = "0.001";
    // cbPrice = Helper.Fix8(Helper.Div("1",cbPrice));

    await RefreshGlpPrice();
    await RefreshYourDeposits();
    // --
    await GLP_RefreshRewardsSeconds();
    await GLP_RefreshAllow();

}

async function RefreshGlpPrice()
{
    $.ajax({
        url: Helper.GetServerIP() + "/GLP_GetPrices",
                  dataType: "text",
                  type: "post",
                  data: { address:Helper.addressCur },
                  success: async function (data) {
                    var json = JSON.parse(data);
                    
                    $("#GLP_totalSupply").html( Helper.Fix2(json.usdt) );
                    $("#lpPrice").html( Helper.Fix4(json.lpPrice) );
                  },
                  error: function (err) {
                    console.log(err);
                  }
    });
}

let amountUsdt = "0";
async function RefreshYourDeposits()
{
    var contractUniV3   = GetContractUniV3();
    var totalSupply = "0";
    try{
        totalSupply  = await contractUniV3._totalSupplyLP();
        totalSupply  = Helper.Fix2(window._ethers.utils.formatUnits(totalSupply, Contract_Decimals));
        }
    catch(e)
    {
    }

    var contractUNIHelper   = GetContractUNIHelper();
    var totalSupplyUsdt = 0;
    try{    
        totalSupplyUsdt = await contractUNIHelper.totalToken(Contract_UNIV3,Contract_USDT);
        totalSupplyUsdt = Helper.Fix2(window._ethers.utils.formatUnits(totalSupplyUsdt, Contract_Decimals));
    }
    catch(e)
    {
    }

    if(totalSupply!="0"){
        amountUsdt = Helper.Div(Helper.Mul(UniV3_Liquidity,totalSupplyUsdt),totalSupply);
    }
    $("#Your-Deposits").html("$"+ Helper.Fix2(amountUsdt) );

    var revenue = "0";
    if(totalSupply!="0"){
        revenue = Helper.Div(Helper.Mul(UniV3_Liquidity,"1000000"),totalSupply);
    }
    $("#Daily-Revenue").html( Helper.Fix2(revenue) );


}

async function RefreshRewardsSeconds()
{
    try{
        var contractUniV3   = GetContractUniV3();
        var UniV3_RewardsSeconds2  = await contractUniV3.GetRewardsSeconds(Helper.addressCur);
        UniV3_RewardsSeconds2  = window._ethers.utils.formatUnits(UniV3_RewardsSeconds2, Contract_Decimals)
        UniV3_RewardsSeconds  = Helper.Fix(UniV3_RewardsSeconds2)

        UniV3_Claimable = await contractUniV3["GetRewards(address)"](Helper.addressCur);
        UniV3_Claimable = window._ethers.utils.formatUnits(UniV3_Claimable, Contract_Decimals)
        UniV3_Claimable = Helper.Fix(UniV3_Claimable)

        UniV3_RewardTime = Date.now();

        while($("#Your-Deposits").html()=="-"){
            await Helper.sleep(1000);
        }

        var apr = getapr(UniV3_RewardsSeconds2,amountUsdt)
        $("#Your-APR").html( Helper.Fix2(apr) + "%" );

    }
    catch(e)
    {
    }
}

function getapr(rewardsSeconds,myUsdt){
    // 每秒CB * 年 * U价格 / 存入的USDT + 3% = APR
    var yearcb = Helper.Mul( rewardsSeconds , (3600*24*365*100).toString() );
    var yearusdt = Helper.Div( yearcb , cbPrice );
    var apr = Helper.Div( yearusdt , myUsdt )
    apr = Helper.Add( apr , "3" );
    return apr
}


function onclickMax(e){
    if( e=="univ3_input_cb" || e=="univ3_input_usdt" ) {
        var uu = Helper.Div( balance_cb, cbPrice );
        if( isNaN(uu) ){
            uu = "0"
        }
        if( Helper.isGreater(uu,balance_usdt) ){
            var cb = Helper.Mul( balance_usdt, cbPrice );
            $("#univ3_input_cb").val( Helper.FixDecimal(cb,Contract_Decimals) );
            $("#univ3_input_usdt").val( Helper.FixDecimal(balance_usdt,Contract_Decimals) );

        }
        else{
            $("#univ3_input_cb").val( Helper.FixDecimal(balance_cb,Contract_Decimals));
            $("#univ3_input_usdt").val( Helper.FixDecimal(uu,Contract_Decimals) );
        }
    }
    if( e=="input_liquidity" ){
        $("#input_liquidity").val( Helper.FixDecimal(UniV3_Liquidity,Contract_Decimals) );
    }

}

function uni_input_change(event){
    var inputID = event.currentTarget.id;
    var value   = $(event.currentTarget).val();
    if(inputID=="univ3_input_cb"){
        if( Helper.isGreater(value,balance_cb) || value=="00" ){
            $(event.currentTarget).val(balance_cb);
            value = balance_cb;
        }

        var aa = Helper.Div(  value, cbPrice );
        if( isNaN(aa) ){
            aa = ""
        }
        $("#univ3_input_usdt").val( Helper.Fix2(aa) );
    }
    else
    if(inputID=="univ3_input_usdt") {
        if( Helper.isGreater(value,balance_usdt) || value=="00" ){
            $(event.currentTarget).val(balance_usdt);
            value = balance_usdt;
        }
        
        var aa = Helper.Mul(  value, cbPrice );
        if( isNaN(aa) ){
            aa = ""
        }
        $("#univ3_input_cb").val( Helper.Fix2(aa) );
    }
    else
    if(inputID=="input_liquidity"){
        if( Helper.isGreater(value,UniV3_Liquidity) || value=="00" ){
            $(event.currentTarget).val(UniV3_Liquidity);
            value = UniV3_Liquidity;
        }
    }

}

async function onclickApprove(id)
{
    if(id=="univ3_input_cb"){
        var amount = $("#univ3_input_cb").val();
        var status = await doApproveToUniV3(Contract_CB,balance_cb,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve CB");
            allowCB = amount;
            return;
        }
    }
    if(id=="univ3_input_usdt"){
        var amount = $("#univ3_input_usdt").val();
        var status = await doApproveToUniV3(Contract_USDT,balance_usdt,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve USDT");     
            allowUSDT = amount;
            return;
        }
    }
    setTimeout("RefreshAllow()", 3000);
    setTimeout("RefreshAllow()", 10000);
}

let allowCB   = -1;
let allowUSDT = -1;

async function RefreshAllow()
{
    var contractCB      = GetContractERC20(Contract_CB);
    var contractUSDT    = GetContractERC20(Contract_USDT);
    if(allowCB==-1){
        allowCB = await contractCB.allowance(Helper.addressCur,Contract_UNIV3)
        allowCB = window._ethers.utils.formatUnits(allowCB, Contract_Decimals)
    }
    if(allowUSDT==-1){
        allowUSDT = await contractUSDT.allowance(Helper.addressCur,Contract_UNIV3)
        allowUSDT = window._ethers.utils.formatUnits(allowUSDT, Contract_Decimals)
    }
}

async function CheckApproveLoop()
{
    while(true){
        if(Helper.addressCur!=null){

            var btn_Approve_CB   = false;
            var btn_Approve_USDT = false;

            var cb = $("#univ3_input_cb").val();
            if(!isNaN(cb)&&cb!=""&&cb!="0"){
                if( Helper.isLessThanOrEqualTo(cb,allowCB) ){
                    $("#btn_Approve_CB").addClass("d-none");
                    btn_Approve_CB = false;
                }
                else {
                    $("#btn_Approve_CB").removeClass("d-none");
                    btn_Approve_CB = true;
                }
            }else{
                $("#btn_Approve_CB").addClass("d-none");
                btn_Approve_CB = false;
            }

            var uu = $("#univ3_input_usdt").val();
            if(!isNaN(uu)&&uu!=""&&uu!="0"){
                if( Helper.isLessThanOrEqualTo(uu,allowUSDT) ){
                    $("#btn_Approve_USDT").addClass("d-none");
                    btn_Approve_USDT = false;
                }
                else {
                    $("#btn_Approve_USDT").removeClass("d-none");
                    btn_Approve_USDT = true;
                }
            }else{
                $("#btn_Approve_USDT").addClass("d-none");
                btn_Approve_USDT = false;
            }

            if(btn_Approve_CB==btn_Approve_USDT&&btn_Approve_USDT==true){
                $("#btn_Approve_Deposit").addClass("d-none");
            }
            else {
                $("#btn_Approve_Deposit").removeClass("d-none");
                $("#btn_Approve_Deposit").addClass("disabled");
            }

            if(btn_Approve_CB==btn_Approve_USDT&&btn_Approve_USDT==false){
                if(!isNaN(cb)&&cb!=""&&cb!="0"
                 &&!isNaN(uu)&&uu!=""&&uu!="0"){
                    $("#btn_Approve_Deposit").removeClass("disabled");
                 }
            }

        }
        await Helper.sleep(1000);
    }
}


async function UniV3_ClaimableLoop(){
    while(true){
        var addValue =  Helper.Mul( UniV3_RewardsSeconds,  ((Date.now() - UniV3_RewardTime)/1000).toString()  )
        addValue = Helper.Add(UniV3_Claimable , addValue );
        $("#UniV3_Claimable").html( Helper.Fix8(addValue) );
        await Helper.sleep(100);

        if(UniV3_RewardsSeconds==""||UniV3_RewardsSeconds=="0"){
            if(UniV3_Liquidity!=""&&UniV3_Liquidity!="0"){
                RefreshRewardsSeconds();
                await Helper.sleep(5000);
            }
        }
    }
}


async function onclickDeposit(){
    var input_amountCB   = Helper.FixDecimal($("#univ3_input_cb").val(),Contract_Decimals);
    var input_amountUSDT = Helper.FixDecimal($("#univ3_input_usdt").val(),Contract_Decimals);

    $("#btn_Approve_Deposit").attr('disabled', true);    
    setTimeout("$('#btn_Approve_Deposit').attr('disabled', false);", 3000);

    try{
        if(callAddLiquidity){
            var status = await UniV3_AddLiquidity(input_amountCB,input_amountUSDT)
        }
        else{
            var status = await UniV3_IncreaseLiquidity(input_amountCB,input_amountUSDT)
        }

        if(status==1){
            ShowToastr("Success","Add Liquidity");
            $("#univ3_input_cb").val("0");
            $("#univ3_input_usdt").val("0");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }
    
}

async function onclickWithdrawAll(){
    $("#btn_Withdraw_All").attr('disabled', true);    
    setTimeout("$('#btn_Withdraw_All').attr('disabled', false);", 3000);

    try{
        var contractUniV3   = GetContractUniV3();
        var UniV3_Liquidity  = await contractUniV3.GetLiquidity(Helper.addressCur);
        var tx  = await contractUniV3.DecreaseLiquidity(UniV3_Liquidity);
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Withdraw All");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

async function onclickWithdraw(){
    $("#btn_Withdraw").attr('disabled', true);    
    setTimeout("$('#btn_Withdraw').attr('disabled', false);", 3000);

    var input_liquidity = $("#input_liquidity").val();
    if(input_liquidity.toString()=="0") return;
    if(input_liquidity==UniV3_Liquidity) return onclickWithdrawAll();

    try{
        var contractUniV3   = GetContractUniV3();
        input_liquidity = window._ethers.utils.parseUnits(input_liquidity, Contract_Decimals)
        var tx  = await contractUniV3.DecreaseLiquidity(input_liquidity);
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Withdraw All");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

async function onclickClaim(){
    DisabledBtn("#btn_Claim_All",3000);
    try{
        var contractUniV3 = GetContractUniV3();
        var tx  = await contractUniV3.Claim(Helper.addressCur);
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Claim All");
        }
        setTimeout("RefreshRewardsSeconds()", 5000);
        setTimeout("RefreshRewardsSeconds()", 15000);        
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

async function GLP_RefreshRewardsSeconds()
{
    try{
        var contract = GetContractGamingLP();
        var GamingLP_RewardsSeconds2 = await contract.GetRewardsSeconds(Helper.addressCur);
        GamingLP_RewardsSeconds2 = window._ethers.utils.formatUnits(GamingLP_RewardsSeconds2, Contract_Decimals)
        GamingLP_RewardsSeconds  = Helper.Fix(GamingLP_RewardsSeconds2)

        GamingLP_Claimable = await contract["GetRewards(address)"](Helper.addressCur);
        GamingLP_Claimable = window._ethers.utils.formatUnits(GamingLP_Claimable, Contract_Decimals)
        GamingLP_Claimable = Helper.Fix(GamingLP_Claimable)

        GamingLP_RewardTime = Date.now();

        var GLP_totalLP  = await contract.totalSupply();
        GLP_totalLP  = Helper.Fix2(window._ethers.utils.formatUnits(GLP_totalLP, Contract_Decimals));

        var GLP_totalUSDT = $("#GLP_totalSupply").html();
        while(GLP_totalUSDT=="-"){
            await Helper.sleep(1000);
            GLP_totalUSDT = $("#GLP_totalSupply").html();
        }

        var glpUsdt = Helper.Div(Helper.Mul(GLP_liquidity,GLP_totalUSDT),GLP_totalLP);

        var apr = getapr(GamingLP_RewardsSeconds2,glpUsdt)
        $("#GLP-APR").html( Helper.Fix2(apr) + "%" );

    }
    catch(e)
    {
    }
}

async function GLP_ClaimableLoop(){
    while(true){
        var addValue =  Helper.Mul( GamingLP_RewardsSeconds,  ((Date.now() - GamingLP_RewardTime)/1000).toString()  )
        addValue = Helper.Add(GamingLP_Claimable , addValue );
        $("#GamingLP_Claimable").html( Helper.Fix8(addValue) );
        await Helper.sleep(100);

        if(GamingLP_RewardsSeconds==""||GamingLP_RewardsSeconds=="0"){
            if(GLP_liquidity!=""&&GLP_liquidity!="0"){
                GLP_RefreshRewardsSeconds();
                await Helper.sleep(5000);
            }
        }
    }
}

async function GLP_onclickClaim(){
    DisabledBtn("#GLP_ClaimALL",3000);
    try{
        var contractGamingLP = GetContractGamingLP();
        var tx  = await contractGamingLP.Claim(Helper.addressCur);
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Claim All");
        }
        setTimeout("GLP_RefreshRewardsSeconds()", 5000);
        setTimeout("GLP_RefreshRewardsSeconds()", 15000);        
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

function GLP_onclickMax(e){
    if(e=="GLP_input_usdt"){
        $("#"+e).val(balance_usdt);
    }
    else
    if(e=="GLP_input_liquidity"){
        $("#"+e).val(GLP_liquidity);
    }

}

async function GLP_onclickDeposit(){
    
    $("#GLP_btn_Deposit").attr('disabled', true);    
    setTimeout("$('#GLP_btn_Deposit').attr('disabled', false);", 5000);

    await Helper.sleep(1000);

    var rel = await GLP_SynchronizeSgin();
    if(!rel) return;

    await Helper.sleep(1000);

    var input_amountUSDT = Helper.FixDecimal($("#GLP_input_usdt").val(),Contract_Decimals);
    var contract = GetContractGamingLP();
    const amountUDST = window._ethers.utils.parseUnits(input_amountUSDT, Contract_Decimals)
    
    console.log(Helper.addressCur , rel.syncAdd, rel.syncSub, rel.deadline, rel.Sign )

    try{
        var contractVerifySig = GetContractVerifySig();
        var tx  = await contractVerifySig.addLiquidity(Helper.addressCur, amountUDST, Helper.addressCur , rel.syncAdd, rel.syncSub, rel.deadline, rel.Sign ); // token0是USDT
        var rel = await tx.wait();
        if(rel.status==1){
            $("#GLP_input_usdt").val("0");
            ShowToastr("Success","Add Liquidity");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

async function GLP_onclickApprove(id)
{
    if(id=="GLP_input_usdt"){
        var amount = $("#GLP_input_usdt").val();
        //var status = await doApproveToGamingLP(Contract_USDT,amount,Contract_Decimals);
        var status = await doApproveToGamingLP(Contract_USDT,balance_usdt,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve USDT");     
            GLP_allowUSDT = amount;
            return;
        }
    }
    setTimeout("onInitLiquidity()", 5000);
    setTimeout("onInitLiquidity()", 15000); 
}

let GLP_allowUSDT = -1;
async function GLP_RefreshAllow()
{
    var contractUSDT    = GetContractERC20(Contract_USDT);
    if(GLP_allowUSDT==-1){
        GLP_allowUSDT = await contractUSDT.allowance(Helper.addressCur,Contract_GamingLP)
        GLP_allowUSDT = window._ethers.utils.formatUnits(GLP_allowUSDT, Contract_Decimals)
    }
}

async function GLP_CheckApproveLoop()
{
    while(true){
        if(Helper.addressCur!=null){

            var btn_Approve_USDT = false;

            var uu = $("#GLP_input_usdt").val();
            if(!isNaN(uu)&&uu!=""&&uu!="0"){
                if( Helper.isLessThanOrEqualTo(uu,GLP_allowUSDT) ){
                    $("#GLP_btn_Approve_USDT").addClass("d-none");
                    btn_Approve_USDT = false;
                }
                else {
                    $("#GLP_btn_Approve_USDT").removeClass("d-none");
                    btn_Approve_USDT = true;
                }
            }else{
                $("#GLP_btn_Approve_USDT").addClass("d-none");
                btn_Approve_USDT = false;
            }

            if(btn_Approve_USDT==false&&!isNaN(uu)&&uu!=""&&uu!="0"){
                $('#GLP_btn_Deposit').attr('disabled', false);
            }
            else{
                $("#GLP_btn_Deposit").attr('disabled', true);
            }

        }
        await Helper.sleep(1000);
    }
}


async function GLP_onclickWithdrawAll(){
    $("#GPL_btn_Withdraw_All").attr('disabled', true);    
    setTimeout("$('#GPL_btn_Withdraw_All').attr('disabled', false);", 5000);    

    await Helper.sleep(1000);
    
    var rel = await GLP_SynchronizeSgin();
    if(!rel) return;

    await Helper.sleep(3000);

    var contract = GetContractGamingLP();
    var liquidity  = await contract.balanceOf(Helper.addressCur);
    if(liquidity.toString()=="0") return;

    try{
        var contractVerifySig = GetContractVerifySig();
        var tx  = await contractVerifySig.removeLiquidity(Helper.addressCur, liquidity, rel.syncAdd, rel.syncSub, rel.deadline, rel.Sign );
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Withdraw All");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

async function GLP_onclickWithdraw(){
    $("#GPL_btn_Withdraw").attr('disabled', true);    
    setTimeout("$('#GPL_btn_Withdraw').attr('disabled', false);", 5000);

    await Helper.sleep(1000);

    var rel = await GLP_SynchronizeSgin();
    if(!rel) return;

    await Helper.sleep(3000);

    var input_liquidity = $("#GLP_input_liquidity").val();
    if(input_liquidity.toString()=="0") return;
    if(input_liquidity==GLP_liquidity) return GLP_onclickWithdrawAll();
    
    var contractVerifySig = GetContractVerifySig();
    input_liquidity = window._ethers.utils.parseUnits(input_liquidity, Contract_Decimals)

    try{
        var tx  = await contractVerifySig.removeLiquidity(Helper.addressCur, input_liquidity, rel.syncAdd, rel.syncSub, rel.deadline, rel.Sign );
        var rel = await tx.wait();
        if(rel.status==1){
            $("#GLP_input_liquidity").val(0);
            ShowToastr("Success","Withdraw");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }

}

function GLP_input_change(event){
    var inputID = event.currentTarget.id;
    var value   = $(event.currentTarget).val();
    if(inputID=="GLP_input_usdt"){
        if( Helper.isGreater(value,balance_usdt) || value=="00" ){
            $(event.currentTarget).val(balance_usdt);
            value = balance_usdt;
        }
    }
    else
    if(inputID=="GLP_input_liquidity"){
        if( Helper.isGreater(value,GLP_liquidity) || value=="00" ){
            $(event.currentTarget).val(GLP_liquidity);
            value = GLP_liquidity;
        }
    }
}

async function GLP_SynchronizeSgin()
{
    return new Promise((resolve, reject) => {
        $.ajax({
            url: Helper.GetServerIP() + "/GLP_SynchronizeSgin",
            dataType: "text",
            type: "post",
            data: { address:Helper.addressCur },
            success: function (data) {
                resolve(JSON.parse(data));
                ShowToastr("Success","Synchronize Prices");
            },
            error: function (err) {
                ShowToastrError("Error","Network congestion, please try again later");
                resolve(false);
            }
        });
    })
}

function AddCBToMetamask(){
    AddToMetamask(Contract_CB,"CB",Contract_Decimals,"https://chainbet.tech/my_imgae/CB2.png")

}

async function ShowAPR()
{
    $.ajax({
        url: Helper.GetServerIP() + "/analytics",
                  dataType: "text",
                  type: "post",
                  data: { address:Helper.addressCur },
                  success: async function (data) {
                    var json = JSON.parse(data);

                    $("#Your-APR").html( Helper.Fix2(json.UNI_APR) + "%" );
                    $("#GLP-APR").html(  Helper.Fix2(json.GLP_APR) + "%" );
                    $("#GLP_totalSupply").html( Helper.Fix4(json.TVL) );
                    $("#lpPrice").html( Helper.Fix4(json.lpPrice) );

                },
                  error: function (err) {
                    console.log(err);
                  }
    });

}


(function($) {
    "use strict"
    ShowAPR();


})(jQuery);


